package com.itheima.zhlx.dao;

import com.itheima.zhlx.entity.PageBean;
import com.itheima.zhlx.entity.Result;
import com.itheima.zhlx.pojo.Goods;
import com.itheima.zhlx.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GoodsDao {
    QueryRunner queryRunner =new QueryRunner(C3P0Utils.getDataSource());
    public List<Goods> goodsfindAll(Integer offset, Integer pageSize){
        String sql ="select * from t_goods LIMIT ?,?";
        Object [] prpams={
                offset,pageSize
        };
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Goods.class),prpams);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }
    public Long countTotal(){
        String sql="select count(*) FROM t_goods";
        try {
           return queryRunner.query(sql,new ScalarHandler<Long>());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0L;
    }
    public Integer addGoodsDao(Goods goods){
        String sql="insert into t_goods values (?,?,?,?,?,?)";
        try {
            return queryRunner.update(sql,null,goods.getName(),goods.getPrice(),goods.getStock(),goods.getDescription(),goods.getTypeId());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 根据id删除商品
     * @param id
     * @return
     */
    public Integer deleteDao(String id){
        String sql =" delete from t_goods where id =?";
        try {
           return queryRunner.update(sql,Integer.parseInt(id));
        } catch (SQLException e) {
            e.printStackTrace();
        }
       return 0;
    }


}
